/*
 * jQuery File Upload Plugin JS Example 8.9.1
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/* global $, window */

$(function () {
    'use strict';
	var fileid = $('#fileupload').attr('recordid');
    // Initialize the jQuery File Upload widget:
    $('#fileupload').fileupload({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        url: baseUrl + '/ajax/upload'
    });
    // Enable iframe cross-domain access via redirect option:
    $('#fileupload').fileupload(
        'option',
        'redirect',
        window.location.href.replace(
            /\/[^\/]*$/,
            '/cors/result.html?%s'
        )
    );
    // Load existing files:
    $('#fileupload').addClass('fileupload-processing');
    $.ajax({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        url: $('#fileupload').fileupload('option', 'url'),
		data: ({recordid : fileid}),
        dataType: 'json',
        context: $('#fileupload')[0]
    }).always(function () {
        $(this).removeClass('fileupload-processing');
    }).done(function (result) {
        $(this).fileupload('option', 'done')
            .call(this, $.Event('done'), {result: result});
		var objfileupload = $('#fileupload');
		setDeleteAttachEven(objfileupload);				
    });


});
function setDeleteAttachEven(objParrent){
    if (typeof(objParrent) ==='undefined') {
        objParrent = $('body');
    }
    $(objParrent).find('button.file_exit').each(function(){
		 $(this).unbind('click').click(function(){
				deletefile_delimitor = '!#~$|*';
				var filecode = $(this).attr('filecode');
				var deleteFileList = $('#deleteFileList').val();
				if(deleteFileList.length>0){
					deleteFileList = deleteFileList + deletefile_delimitor + filecode;
				}else{
					deleteFileList = filecode;
				}
				$('#deleteFileList').val(deleteFileList);
		 });
    })
    $(objParrent).find('button.allselect').bind('click',function() {
		var deletefile_delimitor = '!#~$|*';
		var deleteFileList = '';
		$(objParrent).find('input[type="checkbox"][name="delete"]:checked').each(function(){
			var filecode = $(this).attr('filecode');
			if(filecode.length>0){
				if(deleteFileList.length>0){
					deleteFileList = deleteFileList + deletefile_delimitor + filecode;
				}else{
					deleteFileList = filecode;
				}
			}
		})
		$('#deleteFileList').val(deleteFileList);
    })
}